package com.stu.Demo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @author zy
 * @date 2025/3/3 11:37
 */
public class JdbcDemo {
    public static void main(String[] args) throws ClassNotFoundException {
        /*
        1. 加载数据库驱动类 driver (Java 连接DataBase 使用到的类与接口)
        2. 连接数据库
        3. 执行SQL语句
        4. 获得结果，处理，封装
        5. 关闭数据库连接
         */
        //1. 加载数据库驱动类 driver (Java 连接DataBase 使用到的类与接口)
        Class.forName("com.mysql.cj.jdbc.Driver");
        String url ="jdbc:mysql://localhost:3306/empdb?useSSL=true&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai";
        String username = "root";
        String password = "root";

        //2. 连接数据库
        Connection conn = null;
        try {
            conn =  DriverManager.getConnection(url,username,password);
            System.out.println("连接成功");
        } catch (SQLException throwables) {
            System.out.println("连接失败");
            throwables.printStackTrace();
        }

        //3. 执行SQL语句
        String sql = "insert into emp(empno,ename) values(50,'张三');";
        PreparedStatement preparedStatement = null;
        try {
            preparedStatement = conn.prepareStatement(sql);
            int rows = preparedStatement.executeUpdate();// insert update delete(DML) + DDL
            System.out.println(rows);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally { // 释放资源，节省内存
            //5. 关闭数据库连接
            if(preparedStatement !=null) {
                try {
                    preparedStatement.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }

            if(conn !=null) {
                try {
                    conn.close();
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                }
            }
        }

    }
}
